package com.zhufeng.materialdesign.ui;

import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.zhufeng.materialdesign.bean.AnimalBean;
import com.zhufeng.materialdesign.R;
import com.zhufeng.materialdesign.adapter.AnimalAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private AnimalBean[] animals={new AnimalBean("animal1", R.drawable.animal1),
            new AnimalBean("animal2",R.drawable.animal2),
            new AnimalBean("animal3",R.drawable.animal3),
            new AnimalBean("animal4",R.drawable.animal4),
            new AnimalBean("animal5",R.drawable.animal5),
            new AnimalBean("animal6",R.drawable.animal6),
            new AnimalBean("animal7",R.drawable.animal7),
            new AnimalBean("animal8",R.drawable.animal8),
            new AnimalBean("animal9",R.drawable.animal9),
            new AnimalBean("animal10",R.drawable.animal10)};
    private List<AnimalBean> animalList=new ArrayList<>();
    private AnimalAdapter adapter;
    private SwipeRefreshLayout swipeRefresh;
    private GridLayoutManager layoutManager;
    private int lastVisibleItem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建数据源
        initAnimals();
        RecyclerView recyclerview= (RecyclerView) findViewById(R.id.recycler_view);
        //布局管理器设置布局
        //GridLayoutManager:Gridview
        //LinearLayoutManager:Listview
        //StaggeredGridLayoutManager:瀑布流
        layoutManager=new GridLayoutManager(this,2);
        //设置布局管理器
        recyclerview.setLayoutManager(layoutManager);

        adapter=new AnimalAdapter(animalList);
        recyclerview.setAdapter(adapter);

        //Toolbar替换ActionBar
        Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //初始化DrawerLayout布局，获取ActionBar
        drawerLayout= (DrawerLayout) findViewById(R.id.drawerlayout);
        ActionBar actionBar=getSupportActionBar();
        //获取NavigationView
        NavigationView navigationView= (NavigationView) findViewById(R.id.nav_view);
        //设置返回图标
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.menu);
        }
        //设置菜单监听
        navigationView.setCheckedItem(R.id.nav_call);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                drawerLayout.closeDrawers();
                return true;
            }
        });
        //FloatingActionBar
        FloatingActionButton floatingActionButton= (FloatingActionButton) findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(MainActivity.this, "FAB is Clicked", Toast.LENGTH_SHORT).show();
                //Snackbar  有焦点，多了处理操作
                Snackbar.make(view,"下载完成",Snackbar.LENGTH_SHORT)
                        .setAction("打开", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Toast.makeText(MainActivity.this, "打开文件成功", Toast.LENGTH_SHORT).show();
                            }
                        }).show();
            }
        });

        swipeRefresh= (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        //刷新进度条颜色
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        //下拉刷新监听事件
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //刷新方法
                refreshAnimals();
            }
        });
        //滑动监听实现上拉加载
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem+1  == animalList.size() ){
                    loadMoreData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

    }

    private void loadMoreData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for(int i=0;i<50;i++){
                    Random random=new Random();
                    int index=random.nextInt(animals.length);
                    animalList.add(animals[index]);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    private void refreshAnimals() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initAnimals();
                        adapter.notifyDataSetChanged();
                        //刷新结束，隐藏进度条
                        swipeRefresh.setRefreshing(false);
                    }
                });
            }
        }).start();
    }

    private void initAnimals() {
        animalList.clear();
        for(int i=0;i<50;i++){
            Random random=new Random();
            int index=random.nextInt(animals.length);
            animalList.add(animals[index]);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.save:
                Toast.makeText(this, "save", Toast.LENGTH_SHORT).show();
                break;
            case R.id.delete:
                Toast.makeText(this, "delete", Toast.LENGTH_SHORT).show();
                break;
            case R.id.more:
                Toast.makeText(this, "more", Toast.LENGTH_SHORT).show();
                break;
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return true;
    }
}
